/**
 * Created by gim on 14-1-23.
 */

/**
 * model config setter
 * @type {{createNew: Function}}
 */
Model = {
    createNew: function(path,db,instance,template){
        var model = {};
        model.db = db;
        model.template = getCustomTemplate(template);
        model.name  = getModelNameByPath(path);
        model.className = getClassNameByName(model.name);
        model.instance = getModelByName(model,instance);
        model.config = getConfigInModel(model.instance);
        model.collection = getCollectionName(model.config,model.name);
        return model;
    }
};

function getCustomTemplate(template){
    if (template == null){
        return global._cusTemplate ;
    }
    return template;
}
function getClassNameByName(name){
    return name.substring(0,1).toUpperCase()+name.substring(1);
}

function getModelByName(model,instance){
    if (typeof instance == 'undefined' && typeof global[model.className] == 'undefined' ){
        throw new Error(" class " + model.className + " is undefined !");
    }
    if ( typeof global[model.className] == 'undefined' ){
        global[model.className] = instance;
        return instance;
    }
    else {
        return global[model.className];
    }

}

function getCollectionName(config,modelName){
    return  config['dbBind'] != null
        ? config['dbBind']
        :  modelName;
}

function getConfigInModel(model){
    config = {};
    if (model.dbBind != null){
        config = {'dbBind': model.dbBind};
    }
    return config;
}

function getModelNameByPath(path){
    if (path.search(/\.js/) > -1){
        var namePaths = path.split('/').slice(-1)[0].split('.')[0].split('_'),
            modelName = namePaths[0];
        if (namePaths.length >= 2) {
            for (var i = 1; i <= namePaths.length - 1; i++) {
                modelName += namePaths[i].substring(0,1).toUpperCase()+namePaths[i].substring(1);
            }
        }
        return modelName;
    }
    throw new Error('getModelNameByPath error only support js file');
}